<template>
  <div class="sensitive-content-management" @click.stop>
    <el-tabs v-model="activeTab" class="sensitive-tabs" @tab-click="handleTabClick">
      <el-tab-pane label="敏感内容历史" name="history"></el-tab-pane>
      <el-tab-pane label="敏感词排行" name="ranking"></el-tab-pane>
      <el-tab-pane label="自动审核配置" name="config"></el-tab-pane>
    </el-tabs>

    <!-- 敏感内容历史记录 -->
    <div v-if="activeTab === 'history'" class="sensitive-content">
      <SensitiveHistory @view-detail="handleViewDetail" ref="sensitiveHistoryRef" />
    </div>

    <!-- 敏感词排行 -->
    <div v-else-if="activeTab === 'ranking'" class="sensitive-content">
      <SensitiveWordRanking ref="sensitiveWordRankingRef" />
    </div>

    <!-- 自动审核配置 -->
    <div v-else-if="activeTab === 'config'" class="sensitive-content">
      <AutoReviewConfig ref="autoReviewConfigRef" />
    </div>

    <!-- 敏感内容详情对话框 -->
    <el-dialog
      title="敏感内容详情"
      v-model="sensitiveDetailVisible"
      width="60%"
    >
      <div class="sensitive-detail" v-if="currentSensitiveContent">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="内容类型">
            <el-tag :type="getContentTypeTag(currentSensitiveContent.contentType)">
              {{ getContentTypeText(currentSensitiveContent.contentType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="敏感程度">
            <el-tag :type="getSensitiveLevelTag(currentSensitiveContent.sensitiveDegree)">
              {{ getSensitiveLevelText(currentSensitiveContent.sensitiveDegree) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="检测时间">
            {{ currentSensitiveContent.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="处理状态">
            <el-tag :type="getStatusTag(currentSensitiveContent.status)">
              {{ getStatusText(currentSensitiveContent.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="敏感内容">
            <div class="sensitive-content-text" v-html="highlightSensitiveWords(currentSensitiveContent.content)"></div>
          </el-descriptions-item>
          <el-descriptions-item label="敏感词列表" v-if="currentSensitiveContent.sensitiveWords && currentSensitiveContent.sensitiveWords.length > 0">
            <div class="sensitive-words-list">
              <el-tag
                v-for="(word, index) in currentSensitiveContent.sensitiveWords"
                :key="index"
                type="danger"
                effect="dark"
                size="small"
                style="margin-right: 8px; margin-bottom: 8px;"
              >
                {{ word }}
              </el-tag>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="系统建议" v-if="currentSensitiveContent.suggestion">
            {{ getSuggestionText(currentSensitiveContent.suggestion) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-actions" v-if="currentSensitiveContent.status === 0">
          <el-button type="success" @click="approveSensitiveContent(currentSensitiveContent.id)">通过审核</el-button>
          <el-button type="danger" @click="rejectSensitiveContent(currentSensitiveContent.id)">拒绝内容</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import SensitiveHistory from './SensitiveHistory.vue';
import SensitiveWordRanking from './SensitiveWordRanking.vue';
import AutoReviewConfig from './AutoReviewConfig.vue';
import { approveSensitiveContent as approveContent, rejectSensitiveContent as rejectContent } from '../../api/admin';

const props = defineProps({});
const emit = defineEmits([]);

// 标签页控制
const activeTab = ref('history');
const sensitiveHistoryRef = ref(null);
const sensitiveWordRankingRef = ref(null);
const autoReviewConfigRef = ref(null);

// 敏感内容详情
const sensitiveDetailVisible = ref(false);
const currentSensitiveContent = ref(null);

// 处理自定义tab点击事件，阻止冒泡
const handleTabClick = (tab) => {
  // 更新当前标签页
  activeTab.value = tab.props.name;
  
  // 加载相应内容
  if (tab.props.name === 'history') {
    sensitiveHistoryRef.value?.loadSensitiveHistory();
  } else if (tab.props.name === 'ranking') {
    sensitiveWordRankingRef.value?.loadSensitiveRanking();
  } else if (tab.props.name === 'config') {
    autoReviewConfigRef.value?.loadSensitiveWords();
    autoReviewConfigRef.value?.loadAutoReviewConfig();
  }
  
  // 阻止事件冒泡到外部标签系统
  // 这里不使用事件修饰符，因为tab-click是自定义事件
};

// 监听标签页变化
watch(activeTab, (newTab) => {
  if (newTab === 'history') {
    sensitiveHistoryRef.value?.loadSensitiveHistory();
  } else if (newTab === 'ranking') {
    sensitiveWordRankingRef.value?.loadSensitiveRanking();
  } else if (newTab === 'config') {
    autoReviewConfigRef.value?.loadSensitiveWords();
    autoReviewConfigRef.value?.loadAutoReviewConfig();
  }
});

// 查看敏感内容详情
const handleViewDetail = (content) => {
  currentSensitiveContent.value = content;
  sensitiveDetailVisible.value = true;
};

// 通过敏感内容
const approveSensitiveContent = async (id) => {
  try {
    await ElMessageBox.confirm('确认通过此敏感内容?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await approveContent(id);
    if (response.code === 200) {
      ElMessage.success('操作成功');
      sensitiveDetailVisible.value = false;
      sensitiveHistoryRef.value?.loadSensitiveHistory();
    } else {
      ElMessage.error(response.message || '操作失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error);
      ElMessage.error('操作失败');
    }
  }
};

// 拒绝敏感内容
const rejectSensitiveContent = async (id) => {
  try {
    await ElMessageBox.confirm('确认拒绝此敏感内容?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await rejectContent(id);
    if (response.code === 200) {
      ElMessage.success('操作成功');
      sensitiveDetailVisible.value = false;
      sensitiveHistoryRef.value?.loadSensitiveHistory();
    } else {
      ElMessage.error(response.message || '操作失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error);
      ElMessage.error('操作失败');
    }
  }
};

// 内容类型标签和文本
const getContentTypeTag = (type) => {
  const types = {
    'question': 'primary',
    'answer': 'success',
    'comment': 'info',
    'default': 'info'
  };
  return types[type] || types.default;
};

const getContentTypeText = (type) => {
  const texts = {
    'question': '问题',
    'answer': '回答',
    'comment': '评论',
    'default': '未知'
  };
  return texts[type] || texts.default;
};

// 敏感程度标签和文本
const getSensitiveLevelTag = (level) => {
  const levels = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'info',
    'default': 'info'
  };
  return levels[level] || levels.default;
};

const getSensitiveLevelText = (level) => {
  const texts = {
    'high': '高',
    'medium': '中',
    'low': '低',
    'default': '未知'
  };
  return texts[level] || texts.default;
};

// 处理状态标签和文本
const getStatusTag = (status) => {
  const statusMap = {
    0: 'warning',
    1: 'success',
    2: 'danger',
    'default': 'info'
  };
  return statusMap[status] || statusMap.default;
};

const getStatusText = (status) => {
  const statusMap = {
    0: '待处理',
    1: '已通过',
    2: '已拒绝',
    'default': '未知'
  };
  return statusMap[status] || statusMap.default;
};

// 获取系统建议文本
const getSuggestionText = (suggestion) => {
  const suggestionMap = {
    'approve': '建议通过',
    'reject': '建议拒绝',
    'review': '需要人工审核',
    'default': '无建议'
  };
  return suggestionMap[suggestion] || suggestionMap.default;
};

// 高亮敏感词
const highlightSensitiveWords = (content) => {
  if (!content) return '';
  
  let result = content;
  
  // 如果当前内容中包含敏感词列表，则高亮这些词
  if (currentSensitiveContent.value && currentSensitiveContent.value.sensitiveWords) {
    currentSensitiveContent.value.sensitiveWords.forEach(word => {
      if (word) {
        const regex = new RegExp(word, 'gi');
        result = result.replace(regex, match => `<span class="highlight-sensitive">${match}</span>`);
      }
    });
  }
  
  return result;
};

// 初始化
onMounted(() => {
  // 默认加载敏感内容历史
  nextTick(() => {
    sensitiveHistoryRef.value?.loadSensitiveHistory();
  });
});

// 暴露方法给父组件
defineExpose({
  loadSensitiveHistory: () => sensitiveHistoryRef.value?.loadSensitiveHistory()
});
</script>

<style scoped>
.sensitive-content-management {
  width: 100%;
  position: relative;
  isolation: isolate;
}

.sensitive-tabs {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.sensitive-content {
  margin-top: 20px;
}

.sensitive-detail {
  padding: 10px;
}

.sensitive-content-text {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-all;
  line-height: 1.6;
}

:deep(.highlight-sensitive) {
  color: #F56C6C;
  font-weight: bold;
  background-color: rgba(245, 108, 108, 0.1);
  padding: 0 2px;
  border-radius: 2px;
}

.sensitive-words-list {
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
}

.detail-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  gap: 20px;
}

:deep(.el-descriptions) {
  padding: 15px;
  margin-bottom: 20px;
}

:deep(.el-descriptions__label) {
  width: 120px;
}
</style> 